<template>
  <el-row :gutter="10" style="margin-bottom: 10px">
    <!-- 操作搜索 -->
    <el-col :md="12">
      <el-card class="simple-card">
        <template #header>
          <div class="custom-card-header">
            <SvgIcon icon="edit" size="13" style="margin-right: 5px;"></SvgIcon>
            <span>资金操作</span>
          </div>
        </template>

        <el-form ref="formRef"
                 :model="formData"
                 :rules="formRules"
                 class="full-form"
                 label-width="100px">

          <el-form-item label="资金类型：" prop="capital_type">
            <DictSelect v-model="formData.capital_type" :hidden-keys="[]" :show-default="false" dict-type="money_capital_type" placeholder="请选择资金类型" @change="handleChangeAccountType"/>
          </el-form-item>

          <el-form-item label="用户账号：" prop="account">
            <SelectRemote v-model="formData.account" api-url="/search/user/list" placeholder="请输入要操作的用户账号" @change="handleSelectChange"/>
          </el-form-item>

          <el-form-item label="操作金额：" prop="amount">
            <el-input-number v-model="formData.amount" :max="10000000" :precision="4" controls-position="right" placeholder="请输入操作金额"/>
          </el-form-item>

          <el-form-item label="备注信息：" prop="reason">
            <el-input v-model="formData.reason" placeholder="请输入备注信息"/>
          </el-form-item>

          <el-form-item v-permission="'admin:recharge:submit'" style="margin-bottom:0 !important;">
            <el-button :disabled="!showUserInfo" icon="upload" type="primary" @click="onSubmitForm">提交</el-button>
            <el-button icon="refresh" @click="handleFormReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>

    <!-- 用户信息 -->
    <el-col v-show="showUserInfo" :md="12">
      <el-card class="simple-card user-info">
        <template #header>
          <div class="custom-card-header">
            <SvgIcon icon="info" size="16" style="margin-right: 5px;"></SvgIcon>
            <span>基本信息</span>
          </div>
        </template>

        <el-form ref="userFormRef" :inline="true" :model="userData" class="user-form" label-width="100px">
          <el-form-item label="编号：">
            <UserInfoLink :user-id="userData.id"/>
          </el-form-item>

          <el-form-item label="UID：">
            <span>{{ userData.uid }}</span>
          </el-form-item>

          <el-form-item label="账号：">
            <span>{{ userData.account }}</span>
          </el-form-item>

          <el-form-item label="昵称：">
            <span>{{ userData.nickname }}</span>
          </el-form-item>

          <el-form-item label="花朵：">
            <span>{{ toDecimal(userData.integral, 4) }}</span>
          </el-form-item>

          <el-form-item label="余额：">
            <span>{{ toDecimal(userData.balance, 4) }}</span>
          </el-form-item>

          <el-form-item label="补贴线上：">
            <span>{{ toDecimal(userData.subsidy_xs, 4) }}</span>
          </el-form-item>

          <el-form-item label="补贴线下：">
            <span>{{ toDecimal(userData.subsidy_xx, 4) }}</span>
          </el-form-item>

          <el-form-item label="创客奖金：">
            <span>{{ toDecimal(userData.bonus_zj, 4) }}</span>
          </el-form-item>

          <el-form-item label="合伙人奖金：">
            <span>{{ toDecimal(userData.bonus_hhr, 4) }}</span>
          </el-form-item>

          <el-form-item label="额外奖励：">
            <span>{{ toDecimal(userData.bonus_extra, 4) }}</span>
          </el-form-item>

          <el-form-item label="贡献值余额：">
            <span>{{ toDecimal(userData.contribution_value, 4) }}</span>
          </el-form-item>

          <el-form-item label="消费金余额：">
            <span>{{ toDecimal(userData.balance_xfj, 4) }}</span>
          </el-form-item>

          <el-form-item label="商家花朵：">
            <span>{{ toDecimal(userData.merchant_jf, 4) }}</span>
          </el-form-item>
        </el-form>


      </el-card>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>

import { h, reactive, ref } from 'vue';
import { SvgIcon } from '@/components/icon';
import { defUserInfoData, userInfo } from '@/api/api-user.ts';
import { ElLoading, ElMessageBox, ElNotification, FormInstance, FormRules } from 'element-plus';
import { SelectRemote } from '@/components/other';
import { UserInfoLink } from '@/components/user-info-link';
import { DictSelect } from '@/components/dict-select';
import { toDecimal } from '@/utils';
import { rechargeAdminSubmit } from '@/api/api-finance.ts';

const props = defineProps({
  operateType: {
    type: Number
  },
});

// 默认表单数据
let defaultForm = {
  capital_type: undefined,
  account: undefined,
  amount: undefined,
  reason: undefined,
  password: undefined,
  special: 0,
};

// 表单数据
const formRef = ref<FormInstance>();
const formData = ref({...defaultForm});
const userData = ref({...defUserInfoData});
const userId = ref<any>();
const showUserInfo = ref(false);

// 表单验证规则
const formRules = reactive<FormRules>({
  capital_type: [{required: true, message: '请选择资金类型', trigger: 'blur'}],
  account: [{required: true, message: '请输入用户账号', trigger: 'blur'}],
  amount: [{required: true, message: '请输入操作金额', trigger: 'blur'}],
  reason: [{required: true, message: '请填写备注信息', trigger: 'blur'}]
});

/** 表单提交 */
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      return
    }
    if (props.operateType == 0) {
      // 弹窗确认提示
      ElMessageBox.confirm(h('p', null, ['是否确认对账号 ', h('span', {style: 'font-weight: bold'}, userData.value.account), ' 进行资金操作？',]), {
        title: '提示',
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then((action) => {
        handleSubmitForm(undefined);
      });
    } else {
      // 弹窗输入框
      ElMessageBox.prompt(h('p', null, ['是否确认对账号 ', h('span', {style: 'font-weight: bold'}, userData.value.account), ' 进行资金操作？',]), {
        title: '提示',
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入校检密码',
      }).then((value) => {
        handleSubmitForm(value);
      });
    }
  });
};

/** 提交数据 */
const handleSubmitForm = (password: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在提交中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  formData.value.password = password;
  rechargeAdminSubmit(formData.value).then(() => {
    // 提示信息
    ElNotification({title: '成功', message: '操作成功', type: 'success', duration: 2000});
    // 重置表单数据
    formData.value.amount = undefined;
    formData.value.reason = undefined;
    formData.value.password = undefined;
    // 刷新列表数据
    emit('refresh');
    // 刷新用户数据信息
    loadUserInfo();
  }).finally(() => {
    loading.close();
  })
};

const emit = defineEmits(['change', 'refresh']);
/** 用户选择被改变 */
const handleSelectChange = (val: any) => {
  userId.value = val ? val.id : undefined;
  emit('change', userId.value);
  loadUserInfo();
};

/** 处理资金类型被改变 */
const handleChangeAccountType = () => {
  formData.value.special = 0
};

/** 加载用户信息 */
const loadUserInfo = () => {
  if (!userId || !userId.value || userId.value <= 0) return
  // 重置数据
  userData.value = {...defUserInfoData}
  // 获取用户信息
  userInfo(userId.value).then(res => {
    const {info} = res.data;
    userData.value = info;
    // 设置显示用户数据信息
    showUserInfo.value = true;
  })
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
  // 重置其他数据
  emit('change', undefined);
  userId.value = undefined;
  userData.value = {...defUserInfoData}
  showUserInfo.value = false;
};
</script>

<style lang="scss" scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

@media (max-width: 768px) {
  .el-col {

    &:nth-child(2) {
      margin-top: 10px;
    }
  }
}

.user-form {
  .el-form-item {
    margin-bottom: 3px;
    margin-right: 12px;
    min-width: 220px;
  }
}

</style>
